package org.beiji.services.getawayservice.toolkit;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.system.UserInfo;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.beiji.frameworks.base.constant.UserConstant;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
@Slf4j
public class JWTUtil {

    private static final long EXPIRATION = 86400L;
    public static final String TOKEN_PREFIX = "Bearer ";
    public static final String ISS = "index12306";
    public static final String SECRET = "SecretKey039245678901232039487623456783092349288901402967890140939827";

    /**
     *生成用户的Token
     * @param userInfoDTO
     * @return
     */
    public static String generateAccessToken(UserInfoDTO userInfoDTO){
        Map<String, Object> customerUserMap = new HashMap<>(3);
        customerUserMap.put(UserConstant.USER_ID_KEY, userInfoDTO.getUserId());
        customerUserMap.put(UserConstant.USER_NAME_KEY, userInfoDTO.getUsername());
        customerUserMap.put(UserConstant.REAL_NAME_KEY, userInfoDTO.getRealName());

        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .setSubject(JSONUtil.toJsonStr(customerUserMap))
                .setIssuer(ISS)
                .compact();
        return TOKEN_PREFIX + token;
    }


    public static UserInfoDTO parseJwtToken(String jwtToken){

        // hasText 这个接口通常用作处理jwt带有前缀的
        // 因为他判定条件里面有一项是,必须要有空格
        if(StringUtils.hasText(jwtToken)){
            String actualJwtToken = jwtToken.replace(TOKEN_PREFIX, "");
            try {
                Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJwt(actualJwtToken).getBody();
                Date expiration = claims.getExpiration();
                if (expiration.after(new Date())) {
                    String subject = claims.getSubject();
                    return JSONUtil.toBean(subject, UserInfoDTO.class);
                }
            } catch (ExpiredJwtException e) {

            } catch (Exception e) {
                log.error("JWT Token 解析失败请检查", e);
            }
        }

        return null;
    }





}
